<template>
  <el-menu mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
    <!-- 按照用户指定顺序从左到右排列 -->
    <el-menu-item index="1" style="margin-left: 50px">
      <router-link to="/">首页</router-link>
    </el-menu-item>
    <el-menu-item index="4">
      <router-link to="/blog">博客</router-link>
    </el-menu-item>
    <el-menu-item index="5">
      <router-link to="/hot">热榜</router-link>
    </el-menu-item>
    <el-menu-item index="6">
      <router-link to="/interest">兴趣推荐</router-link>
    </el-menu-item>
    <el-menu-item index="7" style="margin-left: 550px">
      <router-link to="/UserDetail">我的</router-link>
    </el-menu-item>
    <el-menu-item index="9">
      <router-link to="/Publishblog">发布博客</router-link>
    </el-menu-item>
    <el-menu-item index="8">
      <router-link to="/my-blogs">我的博客</router-link>
    </el-menu-item>

    <!-- 头像与用户名（垂直居中）-->
    <el-menu-item class="avatar-username-container">
      <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          @change="handleFileChange" style="margin-bottom: 20px">
        <el-avatar :size="30" :src="imagepath"></el-avatar>
      </el-upload>
      <span style="margin-left: 10px;">{{ currentUser.uname }}</span>
    </el-menu-item>

    <!-- 昵称 -->
    <el-menu-item>
      <span :hidden="!shownickname">昵称:{{ currentUser.userinfo.nickname }}</span>
    </el-menu-item>

    <!-- 注册按钮放在最右侧 -->
    <el-menu-item @click="openRegisterDialog">
      注册
    </el-menu-item>

    <!-- 登录按钮（如果需要可隐藏） -->
    <el-menu-item>
      <span :hidden="!loginbutton" @click="openLoginDialog">登录</span>
    </el-menu-item>
  </el-menu>

  <!-- ------------------------登录对话框  ------------------------------         -->
  <el-dialog v-model="loginDialogVisible" title="用户登录" width="500" height="400" center>
    <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" @submit.prevent="handleLogin"
             style="display: flex; flex-direction: column; justify-content: space-around; align-items: flex-start; height: 100%; padding: 0 20px;">
      <!-- 用户名 -->
      <el-form-item label="用户名" prop="uname" style="width: 100%;">
        <el-input v-model="loginForm.uname" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <!-- 密码 -->
      <el-form-item label="密码" prop="pwd" style="width: 100%;">
        <el-input type="password" v-model="loginForm.pwd" placeholder="请输入密码"></el-input>
      </el-form-item>
      <!-- 验证码 -->
      <el-form-item label="验证码" prop="captcha" style="width: 100%;">
        <div style="display: flex; align-items: center; width: 100%;">
          <el-input v-model="loginForm.captcha" placeholder="请输入验证码" style="flex: 1;"></el-input>
          <img :src="captchaUrl" alt="验证码" style="width: 100px; height: 40px; margin-left: 10px; cursor: pointer;"
               @click="refreshCaptcha">
        </div>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item style="width: 100%; text-align: center;">
        <el-button type="primary" native-type="submit" style="width: 100px;">登录</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 注册对话框------------------------------------------------------------------------------------------ -->
  <el-dialog v-model="centerDialogVisible" title="用户注册" width="500" center>
    <span>请填写以下信息完成注册</span>
    <template #footer>
      <div class="dialog-footer">
        <el-form :model="form" :rules="rules" ref="form" @submit.prevent="handleRegister">
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="uname">
            <el-input v-model="form.uname" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="密码" prop="pwd">
            <el-input type="password" v-model="form.pwd" placeholder="请输入密码"></el-input>
          </el-form-item>
          <!-- 昵称（可选） -->
          <el-form-item label="昵称" prop="userinfo.nickname" required>
            <el-input v-model="form.userinfo.nickname" placeholder="请输入昵称"></el-input>
          </el-form-item>
          <!-- 真实姓名（可选） -->
          <el-form-item label="真实姓名">
            <el-input v-model="form.userinfo.realname" placeholder="请输入真实姓名（可选）"></el-input>
          </el-form-item>
          <!-- 年龄（可选） -->
          <el-form-item label="年龄">
            <el-input v-model.number="form.userinfo.age" type="number" placeholder="请输入年龄"></el-input>
          </el-form-item>
          <!-- 性别（可选） -->
          <el-form-item label="性别" required>
            <el-select v-model="form.userinfo.gender" placeholder="请选择性别（可选）">
              <el-option label="男" value="male"></el-option>
              <el-option label="女" value="female"></el-option>
            </el-select>
          </el-form-item>
          <!-- 个性签名（可选） -->
          <el-form-item label="个性签名">
            <el-input v-model="form.userinfo.signature" placeholder="请输入个性签名（可选）"></el-input>
          </el-form-item>
          <!-- 地区（可选） -->
          <el-form-item label="地区">
            <el-input v-model="form.userinfo.region" placeholder="请输入地区（可选）"></el-input>
          </el-form-item>
          <!-- 学校（可选） -->
          <el-form-item label="学校">
            <el-input v-model="form.userinfo.graduate" placeholder="请输入学校（可选）"></el-input>
          </el-form-item>
          <!-- 提交按钮 -->
          <el-form-item>
            <el-button type="primary" native-type="submit">注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import apiClient from "@/api";

export default {
  name: 'NavBar',
  data() {
    return {
      loginbutton: true,
      shownickname: false,

      currentUser: {
        uname: "",
        userinfo: {
          nickname: "", // 确保 userinfo 始终存在
          imagepath: "defaultpic.png"
        }
      },

      uploadUrl: "/api/uploadimage", // 上传接口地址
      imagepath: "/api/defaultpic.png",

      // 登录所需要的属性

      // 登录的对话框
      loginDialogVisible: false,

      // 登录绑定的表单
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      // 登录的正则
      loginRules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
        captcha: [{required: true, message: '请输入验证码', trigger: 'blur'}]
      },
      // 登录请求的验证码
      captchaUrl: '/api/PicCode',
      //-------------------------------------------------------------------------------------------------------
      // 注册
      centerDialogVisible: false,
      // 注册所需要的表单
      form: {
        userinfo: {}
      },
      // 注册所需要的正则
      rules: {
        uname: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        pwd: [{required: true, message: '请输入密码', trigger: 'blur'}],
        userinfo: {
          age: [{required: false, message: '只能是数字', trigger: 'blur'}],
          nickname: [{required: true, message: '请输入昵称', trigger: 'blur'}],
        }
      }

    }
  }, mounted() {
    this.isLogin();
  },
  methods: {
    openLoginDialog() {
      this.loginForm = {}
      this.loginDialogVisible = true;
    },
    refreshCaptcha() {
      this.captchaUrl = `/api/PicCode?t=${Date.now()}`;
    },
    // 写一个方法; 判断是否登录；
    isLogin() {
      apiClient.get("/api/isLogin").then(res => {
        console.log(res);
        if (res.code === 200) {

          this.currentUser = res.serverData;
          this.$store.dispatch('updateUserInfo', res.serverData);
          // 更新头像路径
          this.imagepath = "/api/" + res.serverData.userinfo.imagepath + `?t=${Date.now()}`;
// 显示昵称
          this.shownickname = true;

          // 隐藏登录按钮
          this.loginbutton = false;

        }
      });
    },
    handleLogin() {
      this.$refs.loginFormRef.validate((valid) => {
        if (valid) {
          apiClient.post("/api/login", this.loginForm).then(res => {
            if (res.code == 200) {
              this.$message({type: "success", message: "登录成功"});
              this.currentUser = res.serverData;
              console.log("登录成功", res.serverData);


              // 使用vuex 全局的保存用户
              // 调用 Vuex 的 action 来保存用户信息

              this.$store.dispatch('updateUserInfo', res.serverData);


              // 更新头像路径
              this.imagepath = "/api/" + res.serverData.userinfo.imagepath + `?t=${Date.now()}`;

              // 显示昵称
              this.shownickname = true;

              // 隐藏登录按钮
              this.loginbutton = false;
              // 关闭登录对话框
              this.loginDialogVisible = false;
            } else {
              throw Error("密码错误");
            }
          }).catch(err => {
            this.$message.error('登录失败，请检查用户名、密码或验证码');
            this.refreshCaptcha();
          });
        } else {
          this.$message.error('信息内容错误');
        }
      });
    },

    openRegisterDialog() {
      // 注意：对象不可以生成，对象的字段可以自定义生成，所以当一个对象里有对象，要自定义的对象，js生成不了！！！！！！！
      // 清空 表单提示信息
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }

      this.form = {userinfo: {}};
      this.centerDialogVisible = true;
    },
    handleRegister() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          apiClient.post("/api/register", this.form).then(res => {
            this.$message({type: "success", message: "注册成功"});
          })
          this.centerDialogVisible = false;
        } else {
          this.$message.error('信息内容错误');
        }
      });
    },
    async handleFileChange(image) {
      try {
        // 检查是否已登录
        const loginCheck = await apiClient.get("/api/isLogin");

        if (loginCheck.code === 500) {
          this.$message.error("你还未登录！");
          return; // 如果未登录，直接返回，不执行后续代码
        }

        // 手动构建表单对象
        const formData = new FormData();
        formData.append('image', image.raw);
        apiClient.post('/api/uploadimage', formData, {
          headers: {'Content-Type': 'multipart/form-data'}
        }).then(res => {
          console.warn(res);
          this.imagepath = "/api" + res.serverData.imagepath + "?data=" + new Date();
          console.log(this.imagepath);
        })
            .catch(error => {
              this.$message.error('上传失败');
              console.error('Upload error:', error);
            });


      } catch (error) {
        // 上传失败提示
        this.$message.error('上传失败');
        console.error('Upload error:', error);
      }
    },
    beforeAvatarUpload(file) {
      const isValidType = file.type === 'image/jpeg' || file.type === 'image/png';
      const isValidSize = file.size / 1024 / 1024 < 3;

      if (!isValidType) {
        this.$message.error('上传头像只能是 JPG/PNG 格式!');
      }
      if (!isValidSize) {
        this.$message.error('上传头像大小不能超过 3MB!');
      }
      return isValidType && isValidSize;
    }
  }
}
</script>

<style>
/* 保持原有 .avatar-uploader 样式不变 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color .3s ease;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

/* 新增样式：使头像和用户名垂直居中 */
.avatar-username-container {
  display: flex;
  align-items: center;
}

/* 头像和用户名容器 - 垂直居中 */
.el-menu-item[index="0"] {
  display: flex;
  align-items: center;
  padding-right: 0;
}

/* 昵称和登录注册容器右对齐 */
.right-aligned {
  float: right;
  margin-left: auto;
  padding: 0 10px;
}
</style>
